/*
 *  Copyright (c) 2011, StripBandunk and/or its affiliates. All rights reserved.
 * 
 *       http://stripbandunk.com/
 * 
 *  STRIPBANDUNK PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package stripbandunk.tutorial.jtreehibernate.service;

import java.util.List;
import org.hibernate.Session;
import stripbandunk.tutorial.jtreehibernate.entity.Category;
import stripbandunk.tutorial.jtreehibernate.helper.HibernateHelper;

/**
 *
 * @author echo
 */
public class CategoryServiceImpl implements CategoryService {

    private Session session;

    public CategoryServiceImpl(Session session) {
        this.session = session;
    }

    public CategoryServiceImpl() {
        this.session = HibernateHelper.getSessionFactory().openSession();
    }

    @Override
    public Category save(String name) {
        session.beginTransaction();

        Category category = new Category();
        category.setName(name);
        session.save(category);

        session.getTransaction().commit();

        return category;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Category> getAll() {
        return session.createCriteria(Category.class).list();
    }

    public void close() {
        this.session.close();
    }
}
